package gui;

import dto.CoberturaDTO;
import dto.ObraSocialDTO;
import dto.ObraSocialPlanDTO;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.InputMap;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import logic.Cobertura;
import logic.ObraSocial;
import logic.ObraSocialPlan;

/**
 *
 * @author lucifer
 */
public class UserCoberturasDialog extends javax.swing.JDialog {

  public static final int RET_CANCEL = 0;
  public static final int RET_OK = 1;

  private ArrayList<CoberturaDTO> coberturas;
  private ArrayList<Integer> osIDs;
  private ArrayList<Integer> planIDs;
  private int idMedico;

  public UserCoberturasDialog(java.awt.Frame parent, boolean modal, int idMedico) {
    super(parent, modal);
    initComponents();

    this.idMedico = idMedico;

    setUpObraSocialComboBox(obraSocialjComboBox);

    preBusqueda();

    String cancelName = "cancel";
    InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
    ActionMap actionMap = getRootPane().getActionMap();
    actionMap.put(cancelName, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        doClose(RET_CANCEL);
      }
    });
  }

  public int getReturnStatus() {
    return returnStatus;
  }

  private void preBusqueda() {
    try {
      coberturas = Cobertura.SearchByMedicoID(idMedico);
      updateCoberturas(coberturas);
    } catch (SQLException ex) {
      Logger.getLogger(UserHorariosDialog.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  private void setUpObraSocialComboBox(JComboBox c) {
    ArrayList<ObraSocialDTO> dtos = null;
    try {
      dtos = ObraSocial.All();
    } catch (Exception e) {
      // no hay obras sociales registradas
      dtos = new ArrayList<>();
    }
    osIDs = new ArrayList<>();
    String[] obraSociales = new String[dtos.size() - 1]; // -1 los particulares

    for (int i = 0; i < obraSociales.length; i++) {
      if (dtos.get(i).getId() == 0) {
        continue;
      }
      osIDs.add(dtos.get(i).getId());
      obraSociales[i] = dtos.get(i).getNombre();
    }
    c.setModel(new DefaultComboBoxModel(obraSociales));
    c.setSelectedIndex(-1);
  }

  private void setUpPlanComboBox(JComboBox c, int idObraSocial) {
    ArrayList<ObraSocialPlanDTO> dtos = null;
    try {
      dtos = ObraSocialPlan.All(idObraSocial);
    } catch (Exception e) {
      // no hay planes para una obra social
      dtos = new ArrayList<>();
    }
    planIDs = new ArrayList<>();
    String[] plans = new String[dtos.size()];

    for (int i = 0; i < plans.length; i++) {
      planIDs.add(dtos.get(i).getId());
      plans[i] = dtos.get(i).getNombre();
    }
    c.setModel(new DefaultComboBoxModel(plans));
    c.setSelectedIndex(-1);
  }

  private void updateCoberturas(ArrayList<CoberturaDTO> dtos) throws SQLException {
    DefaultTableModel m = new DefaultTableModel();
    m.addColumn("Obra Social");
    m.addColumn("Plan");

    for (CoberturaDTO dto : dtos) {
      if (dto.getIdObraSocial() == 0) {
        continue;
      }
      m.addRow(
        new Object[]{
          ObraSocial.SearchByID(dto.getIdObraSocial()).getNombre(),
          ObraSocialPlan.SearchByID(dto.getIdPlanObraSocial()).getNombre()
        }
      );
    }
    coberturasjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    coberturasjTable.setModel(m);
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    okButton = new javax.swing.JButton();
    obraSocialjComboBox = new javax.swing.JComboBox();
    planObraSocialjComboBox = new javax.swing.JComboBox();
    addjButton = new javax.swing.JButton();
    deljButton = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    coberturasjTable = new JTable() {
      public boolean isCellEditable(int i, int j) {
        return false;
      }
    };

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Ingresar Coberturas");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        closeDialog(evt);
      }
    });

    okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/aceptar.png"))); // NOI18N
    okButton.setText("Listo");
    okButton.setMaximumSize(new java.awt.Dimension(112, 27));
    okButton.setMinimumSize(new java.awt.Dimension(112, 27));
    okButton.setPreferredSize(new java.awt.Dimension(112, 27));
    okButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        okButtonActionPerformed(evt);
      }
    });

    obraSocialjComboBox.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        obraSocialjComboBoxActionPerformed(evt);
      }
    });

    addjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/add.png"))); // NOI18N
    addjButton.setMaximumSize(new java.awt.Dimension(44, 25));
    addjButton.setMinimumSize(new java.awt.Dimension(44, 25));
    addjButton.setPreferredSize(new java.awt.Dimension(44, 25));
    addjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addjButtonActionPerformed(evt);
      }
    });

    deljButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/remove.png"))); // NOI18N
    deljButton.setMaximumSize(new java.awt.Dimension(44, 25));
    deljButton.setMinimumSize(new java.awt.Dimension(44, 25));
    deljButton.setPreferredSize(new java.awt.Dimension(44, 25));
    deljButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deljButtonActionPerformed(evt);
      }
    });

    coberturasjTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Obra Social", "Plan"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.String.class
      };
      boolean[] canEdit = new boolean [] {
        false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    coberturasjTable.getTableHeader().setReorderingAllowed(false);
    jScrollPane1.setViewportView(coberturasjTable);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
          .addGroup(layout.createSequentialGroup()
            .addComponent(obraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(planObraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(addjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(deljButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(obraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(planObraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addComponent(addjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(deljButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(12, 12, 12)
        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(12, 12, 12))
    );

    getRootPane().setDefaultButton(okButton);

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
      doClose(RET_OK);
    }//GEN-LAST:event_okButtonActionPerformed

  /**
   * Closes the dialog
   */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
      doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

  private void obraSocialjComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_obraSocialjComboBoxActionPerformed
    int selection = obraSocialjComboBox.getSelectedIndex();
    if (selection == -1) {
      return;
    }
    setUpPlanComboBox(planObraSocialjComboBox, osIDs.get(selection));
  }//GEN-LAST:event_obraSocialjComboBoxActionPerformed

  private void addjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addjButtonActionPerformed
    if (obraSocialjComboBox.getSelectedIndex() == -1 || planObraSocialjComboBox.getSelectedIndex() == -1) {
      JOptionPane.showMessageDialog(this, "No seleccionó todos los ítems. Seleccione todos los ítems de la cobertura, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    CoberturaDTO c = new CoberturaDTO(-1, idMedico, osIDs.get(obraSocialjComboBox.getSelectedIndex()), planIDs.get(planObraSocialjComboBox.getSelectedIndex()));

    coberturas.add(c);
    try {
      updateCoberturas(coberturas);
    } catch (Exception e) {
    }

    obraSocialjComboBox.setSelectedIndex(-1);
    planObraSocialjComboBox.setSelectedIndex(-1);
  }//GEN-LAST:event_addjButtonActionPerformed

  private void deljButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deljButtonActionPerformed
    if (coberturasjTable.getSelectedRow() == -1) {
      JOptionPane.showMessageDialog(this, "No seleccionó ninguna cobertura. Seleccione una cobertura, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    /*
    int ans = JOptionPane.showConfirmDialog(
      this,
      "Eliminar la especialidad " + especialidadSeleccionada.getNombre() + "?",
      "Desea eliminar la especialidad médica seleccionada?",
      JOptionPane.YES_NO_OPTION
    );

    if (ans == JOptionPane.NO_OPTION) {
      return;
    }
    */

    coberturas.remove(coberturasjTable.getSelectedRow());
    try {
      updateCoberturas(coberturas);
    } catch (Exception e) {
    }
  }//GEN-LAST:event_deljButtonActionPerformed
  
  private void doClose(int retStatus) {
    returnStatus = retStatus;
    setVisible(false);
    dispose();
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton addjButton;
  private javax.swing.JTable coberturasjTable;
  private javax.swing.JButton deljButton;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JComboBox obraSocialjComboBox;
  private javax.swing.JButton okButton;
  private javax.swing.JComboBox planObraSocialjComboBox;
  // End of variables declaration//GEN-END:variables
  private int returnStatus = RET_CANCEL;

  public ArrayList<CoberturaDTO> Coberturas() {
    return coberturas;
  }
}
